package com.topscomm.pm.quartz;

import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboDeptEntity;
import com.topscomm.cbo.pojo.CboOrgEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.impl.CboDeptService;
import com.topscomm.cbo.service.impl.CboOrgService;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.pm.controller.PmTaskLogController;
import com.topscomm.pm.pojo.PmTaskEntity;
import com.topscomm.pm.pojo.PmTaskLogEntity;
import com.topscomm.pm.service.impl.PmTaskLogService;
import com.topscomm.pm.service.impl.PmTaskService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.FlowDatacodeCache;
import com.topscomm.tap.common.SessionUserBean;
import com.topscomm.tap.quartz.TapJob;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author: wushenghong
 * @date: 2020/6/4
 * @description: 工作日志自动生成定时任务
 */
public class PmTaskLogApplyJob extends TapJob {

    public final static Logger logger = LoggerFactory.getLogger(PmTaskLogApplyJob.class);

    @Override
    public void run(JobExecutionContext jobExecutionContext) {
        StringBufferProxy sql = new StringBufferProxy();
        String today = cn.hutool.core.date.DateUtil.formatDate(new Date());// 今天
        sql.appendSingle(" enabled=1 ");
        // 查询待生成工作日志的任务，以计划结束时间为节点
        sql.appendSingle("and taskstate = '{0}' and starttime <= {1}", "3", SQLAdapter.toDateLong(today + " 00:00:00"));
        PmTaskService pmTaskService = (PmTaskService) SpringUtil.getBean("pmTaskService");
        List<PmTaskEntity> pmTaskEntityList = pmTaskService.queryByWhere(sql.toString());
        sql.clear();
        if (pmTaskEntityList.size() > 0) {
            for (PmTaskEntity entity : pmTaskEntityList) {
                try {
                    creatTaskLog(entity, today);
                } catch (Exception e) {
                    logger.error("工作日志生成时出现异常（定时任务）！");
                    e.printStackTrace(System.err);
                }
            }
        }
    }

    //工作日志信息生成
    @Transactional(rollbackFor = Exception.class)
    public void creatTaskLog(PmTaskEntity entity, String today) {
        //日志插入及提交
        PmTaskLogController pmTaskLogController = (PmTaskLogController) SpringUtil.getBean("pmTaskLogController");
//        String today = cn.hutool.core.date.DateUtil.formatDate(new Date());
        Map<String, Object> taskLogApplyMap = new HashMap<>();
        Long projectId = entity.getProjectid();
        Long taskId = entity.getId();
        PmTaskLogService pmTaskLogService = (PmTaskLogService) SpringUtil.getBean("pmTaskLogService");
        FlowDatacodeCache flowDatacodeCache = (FlowDatacodeCache) SpringUtil.getBean("flowDatacodeCache");
        List<BasicEntity> entities = new ArrayList<>();
//        // 避免重复插入
//        StringBufferProxy sql = new StringBufferProxy();
//        sql.appendSingle("taskid = {0} and finishtime = {1}", taskId, SQLAdapter.toDateLong(today + " 00:00:00"));
//        List<PmTaskLogEntity> pmTaskLogEntityList = pmTaskLogService.queryByWhere(sql.toString());
//        sql.clear();
        // 当天是工作日
        if (pmTaskLogService.isWorkDate(projectId, ConvertUtil.convertToDate(today))) {
            String leaderCode = entity.getLeadercode();
            String leaderName = entity.getLeadername();
            String participantCodes = entity.getParticipantcodes();
            String participantNames = entity.getParticipantnames();
            if (leaderCode == null || leaderName == null) {
                return;
            }
            // 获取任务参与人信息
            List<String> participantCodeListTemp = new ArrayList<String>();
            List<String> participantNameListTemp = new ArrayList<String>();
            if (participantCodes != null && participantNames != null) {
                participantCodeListTemp = Arrays.asList(participantCodes.split(","));
                participantNameListTemp = Arrays.asList(participantNames.split(","));
            }
            //调用Arrays.asList()生产的List的add、remove方法时报异常,这样转换处理
            List<String> participantCodeList = new ArrayList<String>(participantCodeListTemp);
            List<String> participantNameList = new ArrayList<String>(participantNameListTemp);
            //任务负责人添加至参与人
            participantCodeList.add(leaderCode);
            participantNameList.add(leaderName);
            // 姓名、工号不对应则结束
            if (participantCodeList.size() != participantNameList.size()) {
                return;
            }
            // 循环插入
            Map<String, Object> orgAndDeptMap = new HashMap<>();
            List<Map<String, Object>> flowidList = new ArrayList<>();
            for (int i = 0; i < participantCodeList.size(); i++) {
                // 避免重复插入
                StringBufferProxy sql = new StringBufferProxy();
                sql.appendSingle("taskid = {0} and finishtime = {1} and  usercode = '{2}'", taskId, SQLAdapter.toDateLong(today + " 00:00:00"), participantCodeList.get(i));

                //A、wudaliang为了一天内频繁生成日志，注释掉的
                List<PmTaskLogEntity> pmTaskLogEntityList = pmTaskLogService.queryByWhere(sql.toString());
                sql.clear();
                if (pmTaskLogEntityList.size() != 0) {
                    continue;
                }
                orgAndDeptMap = pmTaskLogService.queryOrgAndDeptByCode(participantCodeList.get(i));
                flowidList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_PmTaskLog", participantCodeList.get(i), "sortcode");
                PmTaskLogEntity pmTaskLogEntity = new PmTaskLogEntity();
                taskLogApplyMap.put("projectid", entity.getProjectid());
                taskLogApplyMap.put("taskid", entity.getId());
                taskLogApplyMap.put("name", entity.getName());
                taskLogApplyMap.put("type", entity.getTasktype());
                taskLogApplyMap.put("content", entity.getExplain());
                taskLogApplyMap.put("finishtime", today);
                taskLogApplyMap.put("username", participantNameList.get(i));
                taskLogApplyMap.put("usercode", participantCodeList.get(i));
                taskLogApplyMap.put("orgcode", orgAndDeptMap.get("orgcode"));
                taskLogApplyMap.put("orgname", orgAndDeptMap.get("orgname"));
                taskLogApplyMap.put("deptcode", orgAndDeptMap.get("deptcode"));
                taskLogApplyMap.put("deptname", orgAndDeptMap.get("deptname"));
                taskLogApplyMap.put("docdate", today);
//                taskLogApplyMap.put("submitdate", new Date());
                taskLogApplyMap.put("flowid", flowidList.size() > 0 ? flowidList.get(0).get("id") : 0);
                pmTaskLogEntity.convertFromMap(taskLogApplyMap);
                entities.add(pmTaskLogEntity);
                taskLogApplyMap.clear();
                orgAndDeptMap.clear();
                flowidList.clear();
            }
        }
        // 批量插入并提交
        if (entities.size() > 0) {
            pmTaskLogService.insertBatch(entities);
            // 系统session
            CboUserService cboUserService = (CboUserService) SpringUtil.getBean("cboUserService");
            CboDeptService cboDeptService = (CboDeptService) SpringUtil.getBean("cboDeptService");
            CboOrgService cboOrgService = (CboOrgService) SpringUtil.getBean("cboOrgService");
            List<CboUserEntity> cboUserEntities = cboUserService.queryByWhere(" code = 'QuartzUser' ");
            List<CboDeptEntity> cboDeptEntities = cboDeptService.queryByWhere(" code = 'D11803'");
            List<CboOrgEntity> cboOrgEntities = cboOrgService.queryByWhere(" code ='D1'");
            SessionUserBean sessionUserBean = new SessionUserBean();
            if (cboUserEntities.size() > 0 && cboDeptEntities.size() > 0 && cboOrgEntities.size() > 0) {
                sessionUserBean.setUser(cboUserEntities.get(0));
                sessionUserBean.setDept(cboDeptEntities.get(0));
                sessionUserBean.setWorkDept(cboDeptEntities.get(0));
                sessionUserBean.setOrg(cboOrgEntities.get(0));
                sessionUserBean.setWorkOrg(cboOrgEntities.get(0));
            }
            // 遍历提交单据
            for (BasicEntity pmTaskLogEntity : entities) {
                // 赋值单号及提交时间
                String docNo = String.valueOf(pmTaskLogEntity.getId());
                docNo = docNo.substring(0, 6) + docNo.substring(9);
                pmTaskLogEntity.setValue("docno", docNo);
                pmTaskLogEntity.setValue("submitdate", new Date());
                Map<String, Object> dataMap = pmTaskLogEntity.convertToMap();
                StringBufferProxy mailtitle = new StringBufferProxy();
                mailtitle.appendSingle("{0}的工作日志待提交，任务：{1}",
                        DateUtil.dateToString(ConvertUtil.convertToDate(dataMap.get("finishtime")), "yyyy-MM-dd"), dataMap.get("name"));
                pmTaskLogService.executeSubmit((TapEntity) pmTaskLogEntity, mailtitle.toString(), sessionUserBean);
                mailtitle.clear();
            }
        }
    }
}
